package com.xiuxia.bopicturebackend.controller;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xiuxia.bopicturebackend.annotation.CheckAuth;
import com.xiuxia.bopicturebackend.common.BaseResponse;
import com.xiuxia.bopicturebackend.common.ResultUtils;
import com.xiuxia.bopicturebackend.constant.UserConstant;
import com.xiuxia.bopicturebackend.exception.ErrorCode;
import com.xiuxia.bopicturebackend.exception.ThrowUtils;
import com.xiuxia.bopicturebackend.manager.auth.SpaceUserAuthManager;
import com.xiuxia.bopicturebackend.model.dto.space.SpaceAddRequestDTO;
import com.xiuxia.bopicturebackend.model.dto.space.SpaceDeleteRequestDTO;
import com.xiuxia.bopicturebackend.model.dto.space.SpaceQueryRequestDTO;
import com.xiuxia.bopicturebackend.model.dto.space.SpaceUpdateRequestDTO;
import com.xiuxia.bopicturebackend.model.entity.Picture;
import com.xiuxia.bopicturebackend.model.entity.Space;
import com.xiuxia.bopicturebackend.model.entity.User;
import com.xiuxia.bopicturebackend.model.enums.SpaceLevelEnum;
import com.xiuxia.bopicturebackend.model.vo.space.SpaceLevel;
import com.xiuxia.bopicturebackend.model.vo.space.SpaceVO;
import com.xiuxia.bopicturebackend.service.PictureService;
import com.xiuxia.bopicturebackend.service.SpaceService;
import com.xiuxia.bopicturebackend.service.SpaceUserService;
import com.xiuxia.bopicturebackend.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @ClassName SpaceController
 * @Author CHENBO
 * @Date 2025/6/24 9:34
 */
@RestController
@RequestMapping("/space")
@Slf4j
@Api(tags = "SpaceController")
public class SpaceController {
    @Resource
    private SpaceService spaceService;
    @Resource
    private UserService userService;
    @Resource
    private PictureService pictureService;
    @Resource
    private SpaceUserAuthManager spaceUserAuthManager;
    @Resource
    private SpaceUserService spaceUserService;
    /**
     * 添加空间
     *
     * @param spaceAddRequestDTO 添加空间请求
     * @param request            请求
     * @return 添加成功后的空间id
     */
    @PostMapping("/add")
    @ApiOperation(value = "添加空间")
    public BaseResponse<Long> addSpace(@RequestBody SpaceAddRequestDTO spaceAddRequestDTO, HttpServletRequest request) {
        User loginUser = userService.getLoginUser(request);
        Long spaceId = spaceService.addSpace(spaceAddRequestDTO, loginUser);
        return ResultUtils.success(spaceId);
    }

    /**
     * 删除空间
     *
     * @param spaceDeleteRequestDTO 删除空间请求
     * @param request               删除空间请求
     * @return 删除成功
     */
    @PostMapping("/delete")
    @ApiOperation(value = "删除空间")
    @Transactional
    public BaseResponse<Boolean> deleteSpace(@RequestBody SpaceDeleteRequestDTO spaceDeleteRequestDTO, HttpServletRequest request) {
        User loginUser = userService.getLoginUser(request);
        ThrowUtils.throwIf(spaceDeleteRequestDTO == null || spaceDeleteRequestDTO.getId() <= 0, ErrorCode.PARAMS_ERROR);
        Long spaceId = spaceDeleteRequestDTO.getId();
        Space oldSpace = spaceService.getById(spaceId);
        ThrowUtils.throwIf(oldSpace == null, ErrorCode.NOT_FOUND_ERROR);
        spaceService.checkSpaceAuth(loginUser, oldSpace);
        List<Picture> pictures = pictureService.getBaseMapper().selectList(new LambdaQueryWrapper<Picture>().eq(Picture::getSpaceId, spaceId));
        for (Picture picture : pictures) {
            pictureService.deletePicture(picture.getId(), loginUser);
        }
        boolean remove = spaceUserService.removeBySpaceId(spaceId);
        ThrowUtils.throwIf(!remove, ErrorCode.OPERATION_ERROR, "用户空间关系删除失败");
        boolean result = spaceService.removeById(spaceId);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(true);
    }

    /**
     * 更新空间
     *
     * @param spaceUpdateRequestDTO 更新空间请求
     * @return 更新成功
     */
    @PostMapping("/update")
    @CheckAuth(mustRole = UserConstant.ADMIN_ROLE)
    @ApiOperation(value = "更新空间（管理员可用）")
    public BaseResponse<Boolean> updateSpace(@RequestBody SpaceUpdateRequestDTO spaceUpdateRequestDTO) {
        ThrowUtils.throwIf(spaceUpdateRequestDTO == null || spaceUpdateRequestDTO.getId() <= 0, ErrorCode.PARAMS_ERROR);
        Space space = new Space();
        BeanUtil.copyProperties(spaceUpdateRequestDTO, space);
        spaceService.fillSpaceBySpaceLevel(space);
        spaceService.validSpace(space, false);
        Long id = spaceUpdateRequestDTO.getId();
        Space oldSpace = spaceService.getById(id);
        ThrowUtils.throwIf(oldSpace == null, ErrorCode.NOT_FOUND_ERROR);
        boolean result = spaceService.updateById(space);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(true);
    }

    /**
     * 分页获取空间列表
     *
     * @param spaceQueryRequestDTO 查询空间请求
     * @param request              请求
     * @return 空间列表
     */
    @PostMapping("/list/page")
    @CheckAuth(mustRole = UserConstant.ADMIN_ROLE)
    @ApiOperation(value = "分页获取空间列表（管理员可用）")
    public BaseResponse<Page<Space>> listSpaceByPage(@RequestBody SpaceQueryRequestDTO spaceQueryRequestDTO, HttpServletRequest request) {
        long current = spaceQueryRequestDTO.getCurrent();
        long size = spaceQueryRequestDTO.getPageSize();
        Page<Space> spacePage = spaceService.page(new Page<>(current, size), spaceService.getQueryWrapper(spaceQueryRequestDTO));
        return ResultUtils.success(spacePage);
    }

    /**
     * 分页获取空间列表
     *
     * @param spaceQueryRequestDTO 获取空间请求
     * @param request              请求
     * @return 封装类列表
     */
    @PostMapping("/list/page/vo")
    @ApiOperation(value = "分页获取空间列表")
    public BaseResponse<Page<SpaceVO>> listSpaceVOByPage(@RequestBody SpaceQueryRequestDTO spaceQueryRequestDTO, HttpServletRequest request) {
        long current = spaceQueryRequestDTO.getCurrent();
        long size = spaceQueryRequestDTO.getPageSize();
        Page<Space> spacePage = spaceService.page(new Page<>(current, size), spaceService.getQueryWrapper(spaceQueryRequestDTO));
        return ResultUtils.success(spaceService.getSpaceVOPage(spacePage, request));
    }

    /**
     * 根据id获取空间封装类
     *
     * @param id      图片id
     * @param request 请求
     * @return 空间封装类
     */
    @GetMapping("/get/vo")
    @ApiOperation(value = "根据id获取图片封装类")
    public BaseResponse<SpaceVO> getSpaceVOById(Long id, HttpServletRequest request) {
        ThrowUtils.throwIf(id <= 0, ErrorCode.PARAMS_ERROR);
        Space space = spaceService.getById(id);
        ThrowUtils.throwIf(space == null, ErrorCode.NOT_FOUND_ERROR);
        SpaceVO spaceVO = spaceService.getSpaceVO(space, request);
        User loginUser = userService.getLoginUser(request);
        List<String> permissionList = spaceUserAuthManager.getPermissionList(space, loginUser);
        spaceVO.setPermissionList(permissionList);
        return ResultUtils.success(spaceVO);
    }

    /**
     * 获取空间等级列表
     *
     * @return 空间等级列表
     */
    @GetMapping("/list/level")
    @ApiOperation(value = "获取空间等级列表")
    public BaseResponse<List<SpaceLevel>> listSpaceLevel() {
        List<SpaceLevel> spaceLevelList = Arrays.stream(SpaceLevelEnum.values()) // 获取所有枚举
                .map(spaceLevelEnum -> new SpaceLevel(
                        spaceLevelEnum.getValue(),
                        spaceLevelEnum.getText(),
                        spaceLevelEnum.getMaxCount(),
                        spaceLevelEnum.getMaxSize()))
                .collect(Collectors.toList());
        return ResultUtils.success(spaceLevelList);
    }

}
